<?php 
/***
    Amrita ITEWS - Copyright (C) 2009 Amrita Vishwa Vidyapeetham, Amritapuri.
                                     (http://www.amrita.edu)
    ***************************************************************************
    This file is part of the Amrita ITEWS distribution.
    Amrita ITEWS is free software; you can redistribute it and/or modify it 
    under the terms of the GNU General Public License (version 2) as published 
    by the Free Software Foundation AND MODIFIED BY the Amrita ITEWS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes Amrita ITEWS without being obliged to provide
    the source code for proprietary components outside of the Amrita ITEWS
    software. Amrita ITEWS is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details. You should have received a copy of the GNU
    General Public License and the Amrita ITEWS license exception along with 
    Amrita ITEWS if not then it can be viewed here: 
    http://itews.amrita.ac.in/license.html.
    
    Documentation, latest information, license and contact details are at:
    http://itews.amrita.ac.in/
 
    Amrita ITEWS source code can be found at:
    http://code.google.com/p/itews"; 
    
    The initial code-base of Amrita ITEWS was developed by Amrita Vishwa 
    Vidyapeetham as part of the project titled,\"Intelligent & Interactive 
    Telematics using Emerging Wireless Technologies for Transport Systems 
    (ITEWS)\" sponsored by Technology Information Forecasting and Assessment 
    Council (TIFAC), India.
***/
?><?php
class MediaDownloadStatusUpdateController extends AppController {
	
	var $name = 'MediaDownloadStatusUpdates';
	var $uses = array('MediaDownloadStatusUpdate', 'Media', 'Configuration', 'ConfigurationParameter', 'TelematicUnit');
	var $components = array('TdcsConfigure'); 
	var $allowCommit = true;
	
	function beforeFilter() {
		
		// Set Timezone
		date_default_timezone_set("Asia/Calcutta");
		$this->setAutoIncremetsForModelObjects();
		
	}

    function index() {
    	
     // Getting GET header if any
		if (isset($_SERVER['HTTP_X_TU_LIST'])) {		
			$tuList  = $_SERVER['HTTP_X_TU_LIST'];
		} else {
			echo "Missing X-TU-List header.\n";
			exit(0);
		}
    	
		// Start transactions
		$this->MediaDownloadStatusUpdate->begin();
		
		// Because CakePHP loads models in a lazy fashion,
		// it's usually not a good idea to create model instances in components.
		// If you need model data in a component,
		// it's best to pass that data in through one of the component's methods:
		$this->TdcsConfigure->setModel($this->ConfigurationParameter);
		
		// Check whether the system is in unit test mode 
		$unitTestMode = $this->TdcsConfigure->isUnitTestMode();
		
		// In Real Time mode service accepts POST data and gets current time of day from system time
		// The message posted to the service has following format: 
		// In Unit Test mode do not accepts any POST data, User has to send the update information
		// throgh GET parameters
		
		if ($unitTestMode) {}
		
    	// Check existance of telematic unit
    	unset($fields);
		$fields['TelematicUnit.telematic_unit_code'] = $tuList;
		if (!$this->TelematicUnit->hasAny($fields)) {
			$this->allowCommit = false;
			echo "Invalid Telematic unit code '$tuList' in supplied data.\n";
			exit(0);
		}
		
		// The POST data has to be read via php://input
		$postMessage = trim(file_get_contents("php://input"));
		
		// Process POST data
		$postLines = explode("\n", $postMessage);
		 
		$downloadStatus = array();
		
		foreach ($postLines as $postLine) {
			if (empty($postLine)) {
				continue;
			}
		 	unset($postField);
			$postField = explode(":", $postLine);
			$postFieldName  = trim($postField[0]);  
			$postFieldValue = trim($postField[1]);
			if ($postFieldName == 'logTime') {
				$downloadStatus[$postFieldName] = trim($postField[1]) . ":" . trim($postField[2]) . ":" . trim($postField[3]) ;
			} else {
				$downloadStatus[$postFieldName] = $postFieldValue;
			}  
		}
		
		// Check whether all required information is present in post data
		if (!array_key_exists('mediacode', $downloadStatus) ||
			!array_key_exists('perDownload', $downloadStatus) || 
			!array_key_exists('dataRate', $downloadStatus) || 
			!array_key_exists('isNotFound', $downloadStatus) || 
			!array_key_exists('lastKnownStatus', $downloadStatus) || 
			!array_key_exists('changedParams', $downloadStatus) || 
			!array_key_exists('nodeCodeAndLatLng', $downloadStatus) || 
			!array_key_exists('logTime', $downloadStatus)) {
				//
				echo "Invalid data.\n";
				exit(0);
		}
		
		// Extract media code
		$mediaCode = $downloadStatus['mediacode'];
		
		// check media code is valid
		unset($fields);
		$fields['Media.media_code'] = $mediaCode;
		if (!$this->Media->hasAny($fields)) {
			echo "Invalid media code '$mediaCode' in supplied data.\n";
			exit(0);
		}
		
		// Check validity of Log Time
		if (!$this->isValidTimeStamp($downloadStatus['logTime'])) {
			echo "Invalid log time '".$downloadStatus['logTime']."' in supplied data.\n";
			exit(0);
		}
		
		// Save download ststus
		// Check for a table record with this media code
		// If such record exists update it
		// Else create a new record

		$data = array();
		
    	/*
		unset($fields);
    	$fields['MediaDownloadStatusUpdate.media_code'] = $mediaCode;
		if ($this->MediaDownloadStatusUpdate->hasAny($fields)) {
			$conditions = array('MediaDownloadStatusUpdate.media_code' => $mediaCode);
			$existingRecordId = $this->MediaDownloadStatusUpdate->field('MediaDownloadStatusUpdate.id', $conditions);
			$data['MediaDownloadStatusUpdate']['id'] = $existingRecordId;  		
		} else {
			$data['MediaDownloadStatusUpdate']['id'] = '';  		
		}
		*/
		
		$data['MediaDownloadStatusUpdate']['id']                                = '';  		
		$data['MediaDownloadStatusUpdate']['telematic_unit_code']               = $tuList; 
		$data['MediaDownloadStatusUpdate']['media_code']                        = $downloadStatus['mediacode'];		
		$data['MediaDownloadStatusUpdate']['percentage_downloaded']             = $downloadStatus['perDownload'];  		
		$data['MediaDownloadStatusUpdate']['media_download_data_rate']          = $downloadStatus['dataRate'];
		$data['MediaDownloadStatusUpdate']['is_not_found']                      = $downloadStatus['isNotFound'];
		$data['MediaDownloadStatusUpdate']['media_download_last_known_status']  = $downloadStatus['lastKnownStatus'];	
		$data['MediaDownloadStatusUpdate']['media_download_changed_parameters'] = $downloadStatus['changedParams'];  		
		$data['MediaDownloadStatusUpdate']['node_details']                      = $downloadStatus['nodeCodeAndLatLng'];  		
		$data['MediaDownloadStatusUpdate']['media_download_logtime']            = $downloadStatus['logTime'];

    	if ($this->MediaDownloadStatusUpdate->save($data)) {
    		$this->allowCommit = true;
    	} else {
    		$this->allowCommit = false;
    	}
    	
    	// Since there is no explicit render function call and we are not loggedin user will be redirected to login screen
		// So afterFilter will not be called automatically 
		$this->afterFilter();
    	
		// Set Headers
		header("Cache-Control: no-cache");
		header("Pragma: no-cache");
		
    	if ($this->allowCommit) {
			$this->MediaDownloadStatusUpdate->commit();
			echo "\n";
			exit(1);
		} else {
			echo "Failed to update media download status.\n";
			$this->MediaDownloadStatusUpdate->rollback();
			exit(0);
		}
		
    }
	
	
	
	function isValidTime($time) {
		
		if (ereg('[^0-9]', $time) || strlen($time) != 4) {
			return false;
		} else {
			$hh = (int) ($time / 100);
			$mm = $time - $hh * 100;
			if ($hh >= 24 || $hh < 0 || $mm >= 60 || $mm < 0 ) {
				return false;
			}  
		}
		return true;
		
	}
	
	
	function isValidUnixTime($unixTime) {
		
		if (ereg('[^0-9]', $unixTime)) {
			return false;
		} else {
			return true;
		}
		
	}
	
	function isValidTimeStamp($timeStamp) {
		
			return true;
		if (ereg('[^0-9]', $timeStamp)) {
			return false;
		} else {
			return true;
		}
		
	}
	
	/*
	function beforeRender() {
		
		if ($this->allowCommit) {
			$this->MediaDownloadStatusUpdate->commit();
		} else {
			$this->MediaDownloadStatusUpdate->rollback();
		}
		
	}
	*/
	function search() {
		
		$this->checkSession();
		$this->checkFileSystemPermission();
		$this->checkMalformedUrl();
				
		$searchFields = array(
			'telematic_unit_code'=>"Telematic Unit",
			'media_code'=>"Media Code",
			'percentage_downloaded'=>"% downloaded",
			'media_download_data_rate'=>"Data Rate",
			'is_not_found'=>"Not found",
			'media_download_last_known_status'=>"Last Status",
			'media_download_changed_parameters'=>"Parameters",
			'node_details'=>"Node details",
			'media_download_logtime'=>"Log Time"
		);
		$searchOrder = array('ASC'=>"Ascending", 'DESC'=>"Descending");
		if(empty($this->data)) {
			list($order, $limit, $page) = $this->setupPagination();
			$conditions = array();
//			$order = 'MediaDownloadStatusUpdate.media_download_logtime DESC';
			if(!is_array($statuses = $this->MediaDownloadStatusUpdate->findAll($conditions, NULL, $order, $limit, $page))) {
				$statuses = array();
			}
			$this->set('statuses', $statuses);
			$this->set('searchOrder', $searchOrder);
			$this->set('searchFields', $searchFields);
		} else {
			//debug($this->data);
			list($order, $limit, $page) = $this->setupPagination();
			$conditions = array();
			$fields = array();
			if ($this->data['MediaDownloadStatusUpdate']['search_fields'] && isset($this->data['MediaDownloadStatusUpdate']['search_fields_select'])) {
				foreach ($this->data['MediaDownloadStatusUpdate']['search_fields_select'] as $fileld) {
					$fields[] = $fileld;
				}
			} else {
				$fields = NULL;
			}
			if($this->data['MediaDownloadStatusUpdate']['search_order'] && isset($this->data['MediaDownloadStatusUpdate']['search_order_select'])) {
				if($this->data['MediaDownloadStatusUpdate']['search_order_direction'] == 'ASC' ){
					$order = 'MediaDownloadStatusUpdate.'.$this->data['MediaDownloadStatusUpdate']['search_order_select'] . ' ASC';
				} else {
					$order = 'MediaDownloadStatusUpdate.'.$this->data['MediaDownloadStatusUpdate']['search_order_select'] . ' DESC';
				}
			}
			if($this->data['MediaDownloadStatusUpdate']['search_key'] && isset($this->data['MediaDownloadStatusUpdate']['search_key_select'])) {
				$conditions = array('MediaDownloadStatusUpdate.'.$this->data['MediaDownloadStatusUpdate']['search_key_select'] . " LIKE '%".$this->data['MediaDownloadStatusUpdate']['search_key_value']."%'");
			}
			
			if(!is_array($statuses = $this->MediaDownloadStatusUpdate->findAll($conditions, $fields, $order, $limit, $page))) {
				$statuses = array();
			}
			$this->set('statuses', $statuses);
			$this->set('searchOrder', $searchOrder);
			$this->set('searchFields', $searchFields);
		}
	}
	
	function purge() {
		
		if(!is_array($mediaDownloadStatusUpdates = $this->MediaDownloadStatusUpdate->findAll(NULL, 'MediaDownloadStatusUpdate.id'))) {
			$mediaDownloadStatusUpdates = array();
		}
		foreach ($mediaDownloadStatusUpdates as $mediaDownloadStatusUpdate) {
			if (!$this->MediaDownloadStatusUpdate->delete($mediaDownloadStatusUpdate['MediaDownloadStatusUpdate']['id'])) {
				$this->Session->setFlash('Unable to delete all records.', 'message_error');
				$this->redirect('/media_download_status_update/search');
			}
		}
		$this->Session->setFlash('The all recodes deleted.', 'message_ok');
		$this->redirect('/media_download_status_update/search');
		
	}
	
	
	function visuals() {
		
		// Set Timezone
		date_default_timezone_set("Asia/Calcutta");
		
		$this->checkSession();
		$this->checkFileSystemPermission();
		$this->checkMalformedUrl();
		$this->setAutoIncremetsForModelObjects();
	
		
		if (!is_array($telematicUnits = $this->TelematicUnit->generateList(NULL, 'telematic_unit_code ASC'))) {
			$telematicUnits = array();
		}
		$this->set('telematicUnits', $telematicUnits);

		if(!is_array($downloadStatuses = $this->MediaDownloadStatusUpdate->findAll())) {
			$downloadStatuses = array();
		}
		foreach ($downloadStatuses as $i => $downloadStatus) {
			$downloadStatuses[$i]['MediaDownloadStatusUpdate']['media_download_data_rate'] = (int) $downloadStatus['MediaDownloadStatusUpdate']['media_download_data_rate']; 	
			//$downloadStatuses[$i]['MediaDownloadStatusUpdate']['media_download_logtime']   = mktime($downloadStatus['MediaDownloadStatusUpdate']['media_download_logtime']); 	
			//$downloadStatuses[$i]['MediaDownloadStatusUpdate']['media_download_logtime']   = mktime(); 	
		}
		
		$xdataA = $this->__buildData($downloadStatuses, 'media_download_logtime');
		$ydataA = $this->__buildData($downloadStatuses, 'media_download_data_rate');
		$this->layout = 'default';
		/*
		print_r($xdataA);
		print_r($ydataA);
		*/
		
	}
	
	function graph() {
		
		header("Cache-Control: no-cache");
		header("Pragma: no-cache");
		
		$graphTypeValuesAllowed = array('DR', 'HM', 'PD', 'LS');
		$groupTypeValuesAllowed = array('PO', 'GT', 'GS', 'AT', 'AS');
		
		/*
		echo "<div style='text-align:left;'>";
		debug($this->data);
		*/
		
		$selectedGraphType    = $this->data['MediaDownloadStatusUpdate']['graph_type']; 
		$selectedGroupType    = $this->data['MediaDownloadStatusUpdate']['group_type'];
		
		if (!in_array($selectedGraphType, $graphTypeValuesAllowed) || !in_array($selectedGroupType, $groupTypeValuesAllowed)) {
			$this->Session->setFlash('Please select a graph type..', 'message_error');
			$this->render('graph', 'ajax');
			exit();	
		}
		
		if (array_key_exists('telematic_unit_code', $this->data['MediaDownloadStatusUpdate'])) {
			$telematicUnitIds     = $this->data['MediaDownloadStatusUpdate']['telematic_unit_code'];
			foreach ($telematicUnitIds as $i=>$telematicUnitId) {
				if (empty($telematicUnitId)) {
					unset($telematicUnitIds[$i]);
				}
			}
			$telematicUnitIdList  = implode(",", $telematicUnitIds);
			if ($selectedGroupType == 'PO' && count($telematicUnitIds) !=1 ) {
				$this->Session->setFlash('Please select only one telematic unit.', 'message_error');
				$this->render('graph', 'ajax');
				exit();	
				
			}
			$telematicUnitIdList = (!empty($telematicUnitIdList)) ? $telematicUnitIdList : 0;

			$conditions = array("TelematicUnit.id IN ($telematicUnitIdList)" );
			$fields     = array("TelematicUnit.telematic_unit_code");
			if(!is_array($telematicUnits = $this->TelematicUnit->findAll($conditions, $fields))) {
				$telematicUnits = array();	
			}
			$telematicUnitCodes = array();
			foreach ($telematicUnits as $telematicUnit) {
				$telematicUnitCodes[] = $telematicUnit['TelematicUnit']['telematic_unit_code'];
			}
			$telematicUnitCodeList  = implode(",", $telematicUnitCodes);
			$telematicUnitCodeList  = (!empty($telematicUnitCodeList)) ? $telematicUnitCodeList: 0;
		} else {
			if (in_array($selectedGroupType, array('PO', 'GT', 'GS'))) {
				$this->Session->setFlash('Please select telematic units.', 'message_error');
				$this->render('graph', 'ajax');
				exit();	
			}
		}
		
		switch ($selectedGroupType) {
			case 'PO' :
			case 'GT' :
			case 'GS' :
				$conditions = array("MediaDownloadStatusUpdate.telematic_unit_code IN ('$telematicUnitCodeList')" );
				break; 
			case 'AT' :
			case 'AS' :
			default:
				$conditions = array();
				break; 
		}
		
		$fields     = array();
		$order      = "MediaDownloadStatusUpdate.media_download_logtime ASC";
		if(!is_array($downloadStatuses = $this->MediaDownloadStatusUpdate->findAll($conditions, $fields, $order))) {
			$downloadStatuses = array();
		}
		$serializedData = serialize($downloadStatuses);
		$urlEncodedData = urlencode($serializedData);
		
		switch ($selectedGraphType) {
			case 'DR' :
				$graphUrl = $this->webroot."media_download_status_update/line/";
				break; 
			case 'HM' :
				//$graphUrl = $this->webroot."media_download_status_update/pie/".$urlEncodedData;
				$graphUrl = $this->webroot."media_download_status_update/pie/";
				break; 
			case 'PD' :
				$graphUrl = $this->webroot."media_download_status_update/bar";
				break; 
			case 'LS' :
				$graphUrl = $this->webroot."media_download_status_update/pie";
				break; 
			default:
				$graphUrl = $this->webroot."media_download_status_update/line";
		}
		/*
		echo "</div>";
		*/
		
		$this->set('graphUrl', $graphUrl);
		$this->render('graph', 'ajax');
	
	}
	
	function pie() {
		
		vendor('jpgraph/jpgraph');
		vendor('jpgraph/jpgraph_pie');
		vendor('jpgraph/jpgraph_pie3d');
		
		header ("Content-type: image/png");
		
		/*
		$serializedData = urldecode($urlDecodedData);
		$mediaDownloadStatusUpdates = unserialize($serializedData);
		
		debug($mediaDownloadStatusUpdates);
		
		$hits   = 0;
		$misses = 0;
		foreach ($mediaDownloadStatusUpdates as $mediaDownloadStatusUpdate) {
			if ($mediaDownloadStatusUpdate['MediaDownloadStatusUpdate']['is_not_found'] == 'T') {
				$hits++;
			} else {
				$misses++;
			}
		}
		*/
		
		$hits   = $this->MediaDownloadStatusUpdate->findCount(array('MediaDownloadStatusUpdate.is_not_found'=>'T'));
		$misses = $this->MediaDownloadStatusUpdate->findCount(array('MediaDownloadStatusUpdate.is_not_found'=>'F'));
		
		$total  = $hits + $misses;

		$hitPer  = ($hits/$total)   * 100;
		$missPer = ($misses/$total) * 100;

		$data  = array($hitPer, $missPer);
		//$data  = array(70,30);
		
		// Create the Pie Graph.
		$graph  = new PieGraph (700,600);
		$graph->SetShadow();
		
		// Set A title for the plot
		$graph->title->Set("Hits vs Misses");
		$graph->title->SetColor("#3388EE");
		
		// Adjust the margin
		$graph->img->SetMargin(50,120,60,120);
		
		$graph->SetBackgroundGradient("#ddeeff","#ffffff",2);
		$graph->SetFrame(true,'#99BBDD',1);
		$graph->SetFrame(true,'#66aaff',1);
		$graph->SetShadow(true, 4, '#f0f0f0');
		
		$p1 = new PiePlot3D($data);
		$p1->SetColor('#3388dd');
		$p1->SetSliceColors(array('#66aaff','#a7d3f8','blue')); 
		$p1->SetLegends(array('Hits', 'Misses'));
		
		//$p1->SetLabels(array('Hits', 'Misses'));
		//$p1->ExplodeAll(); 
		
		$graph->Add( $p1);
		
		// Set the footer
		$graph->footer->left->Set("Amrita Research Labs" );
		$graph->footer->center->Set('');
		$graph->footer->right->Set(date("Y M d G:i:s"));
		$graph->footer->left->SetColor("#aaaaaa");
		$graph->footer->right->SetColor("#aaaaaa");
		$graph->footer->center->SetColor("#aaaaaa");
		
		// Display the grap
		$graph->Stroke();

	}

	function line () {
		
		vendor('jpgraph/jpgraph');
		vendor('jpgraph/jpgraph_line');
		vendor('jpgraph/jpgraph_date');
		
		date_default_timezone_set("Asia/Calcutta");
		
		if(!is_array($downloadStatuses = $this->MediaDownloadStatusUpdate->findAll())) {
			$downloadStatuses = array();
		}
		foreach ($downloadStatuses as $i => $downloadStatus) {
			$downloadStatuses[$i]['MediaDownloadStatusUpdate']['media_download_data_rate'] = (int) $downloadStatus['MediaDownloadStatusUpdate']['media_download_data_rate']; 	
			//$downloadStatuses[$i]['MediaDownloadStatusUpdate']['media_download_logtime']   = mktime($downloadStatus['MediaDownloadStatusUpdate']['media_download_logtime']); 	
			//$downloadStatuses[$i]['MediaDownloadStatusUpdate']['media_download_logtime']   = mktime(); 	
		}
		
		$xdataA = $this->__buildData($downloadStatuses, 'media_download_logtime');
		$ydataA = $this->__buildData($downloadStatuses, 'media_download_data_rate');

		$xdata = $xdataA;  
		$xdata = array(1,3,4,5,6);
		$ydata = $ydataA;
		  
		// Create the graph and specify the scale for both Y-axis
		$graph = new Graph(700,400,"auto");
			
		// Setup X-scale
	/*
		$graph->xaxis->SetTickLabels($xdataA);
	*/
		$graph->SetScale('datint');
		$graph->SetScale('datlin');
		$graph->xaxis->scale->SetDateFormat('Y-md G:i:s');
		$graph->xaxis->SetLabelAngle(90);
	//	$graph->xaxis->scale->SetTimeAlign(MINADJ_15);
		
		
		// Adjust the margin
		$graph->img->SetMargin(50,120,60,120);
		
		$graph->SetBackgroundGradient("#ddeeff","#ffffff",2);
		$graph->SetFrame(true,'#99BBDD',1);
		$graph->SetShadow(true, 3, '#f0f0f0');
		
		// Create the two linear plot
		$lineplot=new LinePlot($ydata, $xdata);
	
		
		// Add the plot to the graph
		$graph->Add($lineplot);
		
		$graph->title->Set("Data rate vs Time");
		$graph->title->SetColor("#3388EE");
		$graph->title->Set(implode(",", $xdataA));
		$graph->xaxis->title->Set("Time");
		$graph->yaxis->title->Set("Data rate");
		
		$graph->title->SetFont(FF_FONT1,FS_BOLD);
		$graph->yaxis->title->SetFont(FF_FONT1,FS_BOLD);
		$graph->xaxis->title->SetFont(FF_FONT1,FS_BOLD);
		
		// Adjust the axis color
		$graph->xaxis->SetColor("#aa0000");
		$graph->yaxis->SetColor("#aa0000");
		
		
		// Set the colors for the plots 
		$lineplot->SetColor("#67a400");
		$lineplot->SetColor("#66aaff");
		$lineplot->SetWeight(2);
		$lineplot->mark->SetType(MARK_FILLEDCIRCLE);
		$lineplot->mark->SetType(MARK_UTRIANGLE);
		$lineplot->mark->SetColor('#508cd5');
		$lineplot->mark->SetFillColor('#508cd5');
		$lineplot->value-> Show();
		
		// Set the legends for the plots
		$lineplot->SetLegend("Plot 1");
		
		// Adjust the legend position
		$graph->legend->Pos(0.05,0.5,"right","center");
		
		// Set the footer
		$graph->footer->left->Set("Amrita Research Labs" );
		$graph->footer->center->Set('');
		$graph->footer->right->Set(date("Y M d G:i:s"));
		$graph->footer->left->SetColor("#aaaaaa");
		$graph->footer->right->SetColor("#aaaaaa");
		$graph->footer->center->SetColor("#aaaaaa");
		
		// Display the grap
		$graph->Stroke();
		
	}
	
	function bar () {
		
		vendor('jpgraph/jpgraph');
		vendor('jpgraph/jpgraph_bar');
		
		if(!is_array($downloadStatuses = $this->MediaDownloadStatusUpdate->findAll())) {
			$downloadStatuses = array();
		}
		foreach ($downloadStatuses as $i => $downloadStatus) {
			$downloadStatus['MediaDownloadStatusUpdate']['percentage_downloaded'] = (int) $downloadStatus['MediaDownloadStatusUpdate']['percentage_downloaded']; 	
			//$downloadStatuses[$i]['MediaDownloadStatusUpdate']['media_download_logtime']   = mktime($downloadStatus['MediaDownloadStatusUpdate']['media_download_logtime']); 	
			//$downloadStatuses[$i]['MediaDownloadStatusUpdate']['media_download_logtime']   = mktime(); 	
		}
		
		$ydata = $this->__buildData($downloadStatuses, 'percentage_downloaded');
		
		$graph = new Graph(700, 600, "auto");
		$graph->SetScale("linlin");	
		
		$graph->title->Set("Percentage downloaded vs Time");
		$graph->title->SetColor("#3388EE");
		$graph->xaxis->title->Set("Time");
		$graph->yaxis->title->Set("Data rate");
		$graph->xaxis->title->SetColor("#ff6200");
		$graph->yaxis->title->SetColor("#ff6200");
		
		$graph->SetBackgroundGradient("#ddeeff","#ffffff",2,GRAD_VER);
		$graph->SetFrame(true,'#99BBDD',1);
		$graph->SetShadow(true, 3, '#f0f0f0');
		/*
		*/

		//$datay=array(12, 8,19,3 ,10,5);

		// Create a bar pot
		$bplot = new BarPlot($ydata);
		$bplot->SetColor("#5588ee");
		$bplot->SetFillColor("#67a400");
		$bplot->SetFillColor("#ff6200");
		$bplot->SetFillColor("#66aaff");
		$bplot->SetFillGradient("#66aaff", '#ffffff', GRAD_VER);
		$bplot->value->Show();
		$bplot->SetValuePos('top');
		//$bplot->SetShadow(true, 3, '#f0f0f0');
		$bplot->SetShadow('#dfefff', 1, 1, true);
		//$bplot->SetMargin(true,'#99BBDD',1);
		$graph->Add($bplot);
		
		// Set the footer
		$graph->footer->left->Set("Amrita Research Labs" );
		$graph->footer->center->Set('');
		$graph->footer->right->Set(date("Y M d G:i:s"));
		$graph->footer->left->SetColor("#aaaaaa");
		$graph->footer->right->SetColor("#aaaaaa");
		$graph->footer->center->SetColor("#aaaaaa");
		
		// Display the grap
		$graph->Stroke();
		
	}
	
	function __buildData($data, $type) {
		
		$dataArray = array(); 
	
		foreach($data as $key => $entry) {
			$value = $entry['MediaDownloadStatusUpdate'];
			$dataArray[] = $value[$type];
		 }
	  
		//return array(11,3,8,12,5,1,9,13,5,7);
	 	return $dataArray;
	 
	}
	 
	function __buildXMLstring ($data, $type) {
	 $counter = 0;
	 $xmlString = ''; 
	
		//print_r($data);
	 foreach($data as $key => $entry) {
	 	$value = $entry['MediaDownloadStatusUpdate'];
	   $xmlString .= '<value xid=\''.$counter.'\'>'.$value[$type].'</value>';
	   $counter++;
	 } 
	 /*
	 echo "<div style='text-align:left;'><pre>";
		print_r($xmlString);
	echo "</pre></div>";
	*/
	 return $xmlString;
	} 
	
	
	
	
}
?>